package com.itheima.miankuangjia;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;

public class BeanFactory3 {
    private BeanFactory3(){}
    private static HashMap<Object,Object> hm=new HashMap<>();
    static {
        try {
            ClassLoader classLoader = BeanFactory3.class.getClassLoader();
            String path = classLoader.getResource("element.xml").getPath();
            Document document = Jsoup.parse(new File(path), "UTF-8");
            Elements elements = document.getElementsByTag("bean");
            for (Element element : elements) {
                String idv= element.attr("id");
                String classv = element.attr("class");
                Class<?> aClass = Class.forName(classv);
                Constructor<?> con = aClass.getDeclaredConstructor();
                con.setAccessible(true);
                Object obj = con.newInstance();
                Elements property = element.getElementsByTag("property");
                for (Element pro : property) {
                    String namev = pro.attr("name");
                    String valuev = pro.attr("value");
                    Field name = aClass.getDeclaredField(namev);
                    name.setAccessible(true);
                    String nametype = name.getType().toString();
                    if (nametype.contains("int")){
                        name.set(obj,Integer.parseInt(valuev));
                    }else {
                        name.set(obj,valuev);
                    }
                }
                hm.put(idv,obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Object getBean(String s){
        return hm.get(s);
    }
}
